package com.xunqi.crm.config.shiro;

import com.xunqi.crm.pojo.User;
import com.xunqi.crm.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

public class MyShiroRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;

    /* 主要是用来进行身份认证的,也就是说验证用户输入的账号和密码是否正确 */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("身份认证: MyShiroRealm.doGetAuthenticationInfo()");
        // 获用户的输入的账号
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String usrName = token.getUsername();
        String usrPassword = new String(token.getPassword());
        System.out.println("usrName:" + usrName);
        System.out.println("usrPassword:" + usrPassword);

        // 通过 username 从数据库中查找 User 对象,如果 找到,没找到
        // 实际项目中,这里可以根据实际情况做缓存,如果不做,Shiro 自己也是有时间间隔机制,2 分内不会重复执行该方法
        User user = userService.getUser(usrName);
       System.out.println("----->> user= " + user.getUsrName());
        if (user == null) {
            throw new UnknownAccountException("账号不存在!");
        } else if (!user.getUsrPassword().equals(usrPassword)) {
            throw new IncorrectCredentialsException("密码不正确!");
        }
        // 认证信息
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user, // 用户
                user.getUsrPassword(), // 密码
                getName() // realm name
        );
        return authenticationInfo;
    }


        /*授权操作*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("权限认证 --> MyShiroRealm.doGetAuthorizationInfo()");
//授权信息
         SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
         //设置权限,如果用戶沒有相应权限，
         //会访问 ShiroConfig 过滤器中 shiroFilter 方法配置的未授权路径
         //将来这里应该是通过数据库动态授权
         authorizationInfo.addStringPermission("用户管理");

         return authorizationInfo;
    }

}
